package com.lujianfei.shortcut

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutManager
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat


class ShortCutUtils {
    companion object {
        /**
         * @param shortLabel 快捷方式显示标题
         * @param id    快捷方式的唯一键
         * @param packageName   目标app的包名
         */
        @SuppressLint("NewApi")
        @RequiresApi(Build.VERSION_CODES.N_MR1)
        fun addShortCut(context: Context, shortLabel: String, id: String, packageName: String) {
            if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
                val shortCutIntent = context.packageManager.getLaunchIntentForPackage(packageName)
                shortCutIntent?.action = Intent.ACTION_VIEW
                //快捷方式创建相关信息。图标名字 id
                val shortcutInfo = ShortcutInfoCompat.Builder(context, id)
                        .setIcon(IconCompat.createWithResource(context, R.mipmap.ic_launcher))
                        .setShortLabel(shortLabel)
                        .setIntent(shortCutIntent!!)
                        .build()
                //创建快捷方式时候回调
                val pendingIntent = PendingIntent.getBroadcast(context, 0, Intent(context, ShortcutReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
                ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, pendingIntent.intentSender)
            }
        }

        /**
         * @param id 判断快捷方式存在的唯一键
         */
        @RequiresApi(Build.VERSION_CODES.N_MR1)
        fun isShortCutExist(context: Context, id: String): Boolean {
            val shortCutManager = context.getSystemService(ShortcutManager::class.java)
            return shortCutManager.pinnedShortcuts.any { it.id == id }
        }
    }
}